package com.szlanyou.thirdsdk.retrofit.interceptor;

import com.szlanyou.thirdsdk.retrofit.client.ClientCommonParamsManager;
import com.szlanyou.thirdsdk.retrofit.util.MyLogUtil;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author : 陈章 on 2016/6/21 0021.
 * function:
 * 拦截添加HttpClient的GET请求请求公共参数
 *
 * 2021.7.19 Deprecated:改在单次请求里实现
 */
@Deprecated
public class GetMethodParamAddInterceptor implements Interceptor {
    private static final String TAG = "GetMethodTokenAddInterceptor";
    private final String METHOD_GET = "GET";
    private ClientCommonParamsManager clientCommonParamsManager;

    public GetMethodParamAddInterceptor(ClientCommonParamsManager clientCommonParamsManager) {
        this.clientCommonParamsManager = clientCommonParamsManager;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        String method = originalRequest.method();
        if (method.equalsIgnoreCase(METHOD_GET)) {
            // 新的请求,添加参数
            Request newRequest = addParam(originalRequest);
            return chain.proceed(newRequest);
        }
        return chain.proceed(originalRequest);
    }

    /**
     * 添加公共参数
     *
     * @param oldRequest
     * @return
     */
    private Request addParam(Request oldRequest) {
        HttpUrl.Builder builder = oldRequest.url()
                .newBuilder();

        StringBuilder commonParamsLogInfo = new StringBuilder();
        commonParamsLogInfo.append("公共请求参数\n");
        for (Iterator<Map.Entry<String, Object>> it = clientCommonParamsManager.getCommonParams().entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<String, Object> item = it.next();
            String key = item.getKey();
            Object value = item.getValue();
            commonParamsLogInfo.append(String.format("key = %s,value = %s\n",key,value));
            builder.setEncodedQueryParameter(key, String.valueOf(value));
        }
        if(clientCommonParamsManager.getCommonParams().size() > 0){
            MyLogUtil.d(TAG,commonParamsLogInfo.toString());
        }

        RequestBody body = oldRequest.body();
        Request newRequest = oldRequest.newBuilder()
                .method(oldRequest.method(), body)
                .url(builder.build())
                .build();
        return newRequest;
    }
}